package cn.edu.cqu.newslab.service.impl;

import java.security.MessageDigest;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

public class MessageDigestFactoryBean implements FactoryBean, InitializingBean {
    private static final String DEFAUL_ALGORITHM = "MD5";
    private String algorithm = DEFAUL_ALGORITHM;
    private MessageDigest messageDigest;
    
    //FactoryBean接口声明了3个方法，getObject、getObjectType、isSingleton
    
    /**
     * getObject（）方法以获取FactoryBean创建的对象
     * 在此处getObject返回存在的MessageDigest实例
     */
    @Override
	public Object getObject() throws Exception {
		return this.messageDigest.clone();
	}
    /**
     * getObjectType()方法告诉Spring你的FactoryBean将返回什么类型的对象
     * 此处getObjectType返回MessageDigest.class
     */
	@Override
	public Class getObjectType() {
		return MessageDigest.class;
	}
	/**
	 * isSingleton()告诉Spring，正在被FactoryBean管理的是否为单例实例
	 */
	@Override
	public boolean isSingleton() {
		return true;
	}
	

	public void setAlgorithm(String algorithm) {
		this.algorithm = algorithm;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		this.messageDigest = MessageDigest.getInstance(this.algorithm);
	}
}
